﻿using System;
using System.Globalization;
using System.Net.Configuration;
using System.Text;

namespace Salient.Web.Administration.AppConfig
{
    public partial class SmtpSettings : ApplicationConfigurationPage
    {
        #region AuthenticateMode enum

        public enum AuthenticateMode
        {
            None = 0,
            Basic = 1,
            NTLM = 2,
        }

        #endregion

        private int PasswordCharLen
        {
            get
            {
                object o = ViewState["!PasswordCharLen"];
                if (o == null)
                {
                    return 0;
                }
                return (int) o;
            }
            set { ViewState["!PasswordCharLen"] = value; }
        }

        private WebAdminWithConfirmation Master
        {
            get { return (WebAdminWithConfirmation) base.Master; }
        }

        public void Authentication_ValueChanged(object sender, EventArgs e)
        {
            ToggleSenderInfoUI(BasicRadioButton.Checked);
        }

        private void Page_Load()
        {
            string appPath = ApplicationPath;
            if (!IsPostBack)
            {
                if (!String.IsNullOrEmpty(appPath))
                {
                    ConfigureSMTPTitle.Text = String.Format((string) GetLocalResourceObject("TitleForSite"), appPath);
                }

                System.Configuration.Configuration config = OpenWebConfiguration(appPath);
                var netSmtpMailSection = (SmtpSection) config.GetSection("system.net/mailSettings/smtp");

                ServerNameTextBox.Text = netSmtpMailSection.Network.Host;
                ServerPortTextBox.Text = Convert.ToString(netSmtpMailSection.Network.Port, CultureInfo.InvariantCulture);

                FromTextBox.Text = netSmtpMailSection.From;

                AuthenticateMode authenticateMode;
                if (netSmtpMailSection.Network.DefaultCredentials)
                {
                    authenticateMode = AuthenticateMode.NTLM;
                }
                else
                {
                    authenticateMode = AuthenticateMode.None;
                    if (!String.IsNullOrEmpty(netSmtpMailSection.Network.UserName))
                    {
                        authenticateMode = AuthenticateMode.Basic;
                    }
                }

                switch (authenticateMode)
                {
                    case AuthenticateMode.None:
                        NoneRadioButton.Checked = true;
                        break;
                    case AuthenticateMode.Basic:
                        BasicRadioButton.Checked = true;
                        break;
                    case AuthenticateMode.NTLM:
                        NTLMRadioButton.Checked = true;
                        break;
                    default:
                        throw new Exception((string) GetLocalResourceObject("UnexpectedSmtpField"));
                }

                if (netSmtpMailSection.Network.UserName != null)
                {
                    UserNameTextBox.Text = netSmtpMailSection.Network.UserName;
                }

                PasswordCharLen = 0;
                PasswordTextBox.Text = String.Empty;
                if (netSmtpMailSection.Network.Password != null)
                {
                    PasswordCharLen = netSmtpMailSection.Network.Password.Length;

                    var szFakePassword = new StringBuilder(25);
                    for (int i = 0; i < PasswordCharLen; i++)
                    {
                        szFakePassword.Append("*");
                    }

                    PasswordTextBox.Text = szFakePassword.ToString();
                }

                ToggleSenderInfoUI(authenticateMode == AuthenticateMode.Basic);
            }
        }

        public void SaveButton_Click(object sender, EventArgs e)
        {
            System.Configuration.Configuration config = OpenWebConfiguration(ApplicationPath);
            var netSmtpMailSection = (SmtpSection) config.GetSection("system.net/mailSettings/smtp");

            netSmtpMailSection.Network.Host = ServerNameTextBox.Text;
            netSmtpMailSection.Network.Port = Convert.ToInt32(ServerPortTextBox.Text, CultureInfo.InvariantCulture);

            netSmtpMailSection.From = FromTextBox.Text;

            AuthenticateMode authenticationMode = AuthenticateMode.None;
            if (NoneRadioButton.Checked)
            {
                authenticationMode = AuthenticateMode.None;
            }
            else if (BasicRadioButton.Checked)
            {
                authenticationMode = AuthenticateMode.Basic;
            }
            else
            {
                authenticationMode = AuthenticateMode.NTLM;
            }


            if (authenticationMode == AuthenticateMode.None)
            {
                netSmtpMailSection.Network.DefaultCredentials = false;
                netSmtpMailSection.Network.UserName = String.Empty;
                netSmtpMailSection.Network.Password = String.Empty;
            }
            else if (authenticationMode == AuthenticateMode.Basic)
            {
                netSmtpMailSection.Network.DefaultCredentials = false;
                netSmtpMailSection.Network.UserName = UserNameTextBox.Text;
                if (PasswordCharLen != 0)
                {
                    var szFakePassword = new StringBuilder(25);
                    for (int i = 0; i < PasswordCharLen; i++)
                    {
                        szFakePassword.Append("*");
                    }

                    if (0 == string.Compare(PasswordTextBox.Text, szFakePassword.ToString()))
                    {
                        // user didn't change anything, we don't have to re-set something we didn't change.
                    }
                    else
                    {
                        // password was changed, set it
                        netSmtpMailSection.Network.Password = PasswordTextBox.Text;
                    }
                }
                else
                {
                    netSmtpMailSection.Network.Password = PasswordTextBox.Text;
                }
            }
            else
            {
                netSmtpMailSection.Network.DefaultCredentials = true;
                netSmtpMailSection.Network.UserName = String.Empty;
                netSmtpMailSection.Network.Password = String.Empty;
            }

            SaveConfig(config);

            // Go to confirmation UI
            Master.SetDisplayUI(true);
        }

        private void ToggleSenderInfoUI(bool enabled)
        {
            UserNameLabel.Enabled = enabled;
            UserNameTextBox.Enabled = enabled;
            PasswordLabel.Enabled = enabled;
            PasswordTextBox.Enabled = enabled;
        }

        // Confirmation's related handlers
        public void ConfirmOK_Click(object sender, EventArgs e)
        {
            ReturnToPreviousPage(sender, e);
        }
    }
}